package com.demo.grpc;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;

public class HelloClient {

    public static void main(String[] args) {

        //使用usePlaintext，否则使用加密连接
        ManagedChannelBuilder<?> channelBuilder = ManagedChannelBuilder.forAddress("localhost", 8899).usePlaintext();
        ManagedChannel channel = channelBuilder.build();


        //双向流式通信
        StreamObserver<HelloWorldProtos.HelloStreamRequest> requestObserver =
                HelloServiceGrpc.newStub(channel)
                        .clientServerStream(new StreamObserver<HelloWorldProtos.HelloStreamResponse>() {
            @Override
            public void onNext(HelloWorldProtos.HelloStreamResponse value) {
                System.out.println("=HelloClient.onNext=>");
                System.out.println("=HelloClient.onNext=>response:" + value.getResponseInfo());
            }

            @Override
            public void onError(Throwable t) {
                System.out.println("=HelloClient.onError=>");
                t.printStackTrace();
            }

            @Override
            public void onCompleted() {
                System.out.println("=HelloClient.onCompleted=>");
            }
        });

        requestObserver.onNext(HelloWorldProtos.HelloStreamRequest.newBuilder().setRequestInfo("hello server1").build());
        requestObserver.onNext(HelloWorldProtos.HelloStreamRequest.newBuilder().setRequestInfo("hello server2").build());
        requestObserver.onNext(HelloWorldProtos.HelloStreamRequest.newBuilder().setRequestInfo("hello server3").build());
        requestObserver.onNext(HelloWorldProtos.HelloStreamRequest.newBuilder().setRequestInfo("hello server4").build());
        requestObserver.onCompleted();


        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
